package demo;

import cn.hutool.core.net.Ipv4Util;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.regex.Pattern;

/**
 * @author lingkang
 * @create by 2024/5/17 15:06
 */
public class Demo15_ip {
    // 正则表达式匹配CIDR格式，例如：192.168.1.0/24
    private static final Pattern CIDR_PATTERN = Pattern.compile(
            "^([0-9]{1,3}\\.){3}[0-9]{1,3}/([0-9]{1,2})$"
    );

    // 检查IP是否在网段内
    public static boolean isIpInRange(String ip, String range) throws UnknownHostException {
        // 解析CIDR表示法
        String[] parts = range.split("/");
        if (parts.length != 2) {
            throw new IllegalArgumentException("Invalid CIDR format");
        }
        String networkAddress = parts[0];
        int networkPrefix = Integer.parseInt(parts[1]);

        // 创建网络地址和子网掩码
        InetAddress network = InetAddress.getByName(networkAddress);
        byte[] networkBytes = network.getAddress();
        byte[] subnetMask = getSubnetMask(networkPrefix);

        // 解析目标IP地址
        InetAddress target = InetAddress.getByName(ip);
        byte[] targetBytes = target.getAddress();

        // 进行掩码运算，比较网络地址是否相同
        for (int i = 0; i < networkBytes.length; i++) {
            if ((networkBytes[i] & subnetMask[i]) != (targetBytes[i] & subnetMask[i])) {
                return false;
            }
        }
        return true;
    }

    // 根据网络前缀长度获取子网掩码
    private static byte[] getSubnetMask(int networkPrefix) {
        byte[] mask = new byte[4];
        int maskBits = 0xFFFFFFFF >> (32 - networkPrefix);
        mask[0] = (byte) (maskBits >>> 24);
        mask[1] = (byte) (maskBits >>> 16);
        mask[2] = (byte) (maskBits >>> 8);
        mask[3] = (byte) (maskBits >>> 0);
        return mask;
    }

    public static void main(String[] args) throws UnknownHostException {
        String ip = "192.168.1.10";
        String range = "192.168.1.0/24";
        boolean isInRange = isIpInRange(ip, range);
        System.out.println("IP " + ip + " is in range " + range + ": " + isInRange);
        System.out.println(Ipv4Util.matches("192.168.1.*","192.168.1.10"));;
    }

}
